<script lang="ts" setup>
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { warnBox } from '@/utils/utils'
import EditDialog from './components/EditDialog.vue'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { changeJobStatus, delJob, getListJob, jobExport, runJob } from '@/api/monitor/job'
import { downloadBlobFile } from '@/utils'
import type { Job, JobQueryParams } from '@/api/monitor/job/type'
import PreviewDialog from './components/PreviewDialog.vue'
import { debounce } from 'es-toolkit'
import { getDicts } from '@/api/system/dict'
import { formatDate } from '@/utils/day'

const jobGroupOptions = ref<IGetDictsRes>([])
const statusOptions = ref<IGetDictsRes>([])
const router = useRouter()

// form
const formValue = ref<JobQueryParams & { daterange?: string[] }>({
	jobName: '',
	jobGroup: '',
	status: '',
	daterange: []
})

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '任务名称',
		prop: 'jobName'
	},
	{
		type: 'select',
		label: '任务组名',
		prop: 'jobGroup',
		options: jobGroupOptions as unknown as any[],
		attrs: {
			style: 'width: 200px'
		}
	},
	{
		type: 'select',
		label: '任务状态',
		prop: 'status',
		options: statusOptions as unknown as any[],
		attrs: {
			style: 'width: 200px'
		}
	}
])

// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})

const tableData = ref<Job[]>([])
const columns = ref<TableColums[]>([
	{
		type: 'index',
		label: '序号',
		align: 'center',
		width: 60
	},
	{
		label: '任务编号',
		prop: 'jobId'
	},
	{
		label: '任务名称',
		prop: 'jobName'
	},
	{
		label: '任务组名',
		prop: 'jobGroup',
		type: 'slot'
	},
	{
		label: '调用目标字符串',
		prop: 'invokeTarget'
	},
	{
		label: 'cron执行表达式',
		prop: 'cronExpression'
	},
	{
		label: '状态',
		prop: 'status',
		type: 'slot'
	},
	{
		label: '创建时间',
		prop: 'createTime',
		formatter: row => formatDate(row.createTime)
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: '350px',
		align: 'center'
	}
])

// dialog
const editDialogRef = useTemplateRef('editDialogRef')
// const previewDialogRef = useTemplateRef('previewDialogRef')

const getTableData = async () => {
	try {
		loading.value = true
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value
		}

		const res = await getListJob(params)
		tableData.value = res.data.rows
		page.value.total = res.data.total
	} finally {
		loading.value = false
	}
}
// 新增修改弹窗

const handelAdd = () => {
	editDialogRef.value?.init('add')
}

const handelEdit = (row: Job) => {
	editDialogRef.value?.init('edit', row.jobId)
}

const handelDelete = async (jobId: string) => {
	await warnBox({
		title: '提示',
		message: `是否确认删除定时任务编号为"${jobId}"的数据项？`
	})
	await delJob(jobId)
	ElMessage.success('删除成功')
	getTableData()
}

const handleRun = (row: Job) => {
	ElMessageBox({
		type: 'warning',
		title: '提示',
		message: '确认要立即执行一次"' + row.jobName + '"任务吗?',
		showCancelButton: true,
		cancelButtonText: '取消',
		confirmButtonText: '确定'
	}).then(() => {
		runJob(row.jobId, row.jobGroup).then(() => {
			ElMessage.success('执行成功')
		})
	})
}
// 预览弹窗
const previewDialogShow = ref(false)
const previewDialogId = ref('')
const handleView = (row: Job) => {
	// 任务详细
	previewDialogId.value = row.jobId + ''
	previewDialogShow.value = true
}

const handleJobLog = (jobId: string) => {
	router.push('/monitor/job-log/index/' + jobId)
}

function handleStatusChange(row: Job) {
	const preStatus = row.status === '0' ? '1' : '0'
	const flagMsg = row.status === '0' ? '启用' : '停用'

	ElMessageBox({
		title: '提示',
		type: 'warning',
		message: `确认要"${flagMsg}""${row.jobName}"任务吗?`,
		showCancelButton: true,
		cancelButtonText: '取消',
		confirmButtonText: '确定'
	})
		.then(async () => {
			await changeJobStatus(row.jobId, row.status)
			ElMessage.success(flagMsg + '成功')
			getTableData()
		})
		.catch(() => {
			row.status = preStatus
		})
}

const handleExport = debounce(() => exportFn(), 800, {
	edges: ['leading']
})

// 导出
const exportFn = () => {
	const params = {
		pageNum: page.value.currentPage,
		pageSize: page.value.pageSize,
		...formValue.value
	}
	jobExport(params).then(data => {
		downloadBlobFile(data.data, data.filename ? data.filename : `job_${new Date().getTime()}.xlsx`)
	})
}

function init() {
	getDicts('sys_sys_job_group').then(data => {
		jobGroupOptions.value = data
	})
	getDicts('sys_sys_job_status').then(data => {
		statusOptions.value = data
	})
}

onMounted(() => {
	init()
	getTableData()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['monitor:job:add'])"
						type="primary"
						@click="handelAdd"
					>
						新增
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:job:export'])"
						@click="handleExport"
					>
						导出
					</el-button>
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['monitor:job:edit'])"
						type="primary"
						link
						@click="handelEdit(row)"
					>
						修改
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:job:changeStatus'])"
						type="primary"
						link
						@click="handleRun(row)"
					>
						执行一次
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:job:query'])"
						type="primary"
						link
						@click="handleView(row)"
					>
						任务详细
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:job:query'])"
						type="primary"
						link
						@click="handleJobLog(row.jobId)"
					>
						调度日志
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:job:remove'])"
						type="danger"
						link
						@click="handelDelete(row.jobId)"
					>
						删除
					</el-button>
				</template>
				<template #jobGroup="{ value }">
					<DictTag
						:value="value"
						:options="jobGroupOptions"
					/>
				</template>
				<template #status="{ row }">
					<el-switch
						v-model="row.status"
						:active-value="0"
						:inactive-value="1"
						@click="handleStatusChange(row)"
					/>
				</template>
			</QTable>
		</div>
		<!-- 
		
		<PreviewDialog ref="previewDialogRef" /> -->
		<EditDialog
			ref="editDialogRef"
			:job-group-options="jobGroupOptions"
			@refresh="getTableData"
		/>
		<PreviewDialog
			v-model:previewDialogShow="previewDialogShow"
			:preview-dialog-id="previewDialogId"
		/>
	</div>
</template>
